import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { routerRedux, Route } from 'dva/router';
import { connect } from 'dva';
import {
  Table,
  Icon,
  Divider,
  Form,
  Select,
  DatePicker,
  Input,
  Card,
  Tag,
  Avatar,
  Checkbox,
  Rate,
  Progress,
  Button,
  Dropdown,
  Row,
  Col,
  Modal,
  Collapse,
  message,
  List,
  Radio,
  Tabs,
  Spin,
} from 'antd';

import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import FooterToolbar from 'components/FooterToolbar';
import querystring from 'querystring';
import ApplyOrderDisplayer from '../../../components/Falcon/ApplyOrderDisplayer';
import CustomerList from '../../../components/Falcon/CustomerList';
import ImageUploader from '../../../components/Falcon/Attachment/ImageUploader';
import CustomerChecker from '../../../components/Falcon/Customer/CustomerChecker';
import AssetChecker from '../../../components/Falcon/Asset/AssetChecker';
import RepaymentAbilityChecker from '../../../components/Falcon/RepaymentAbility/RepaymentAbilityChecker';
import DescriptionList from '../../../components/DescriptionList';
import styles from './style.less';
import nopictures from '../../../assets/nopictures3.svg';

const Panel = Collapse.Panel;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const Option = Select.Option;
const { TabPane } = Tabs;
const ButtonGroup = Button.Group;
const { Description } = DescriptionList;

const formItemLayout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
};

@connect(({ risk }) => ({
  risk,
}))
@Form.create()
export default class ReviewDetail extends PureComponent {
  state = {
    width: '100%',
    projectId: '',
    taskId: '',
    modalVisible: false,
    progressVisible: false,
    approvalResult: false,
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    // console.log('params', params);
    this.setState({
      projectId: params.id,
      taskId: params.taskId,
    });
    dispatch({
      type: 'risk/getBusinessDetails',
      payload: {
        projectId: params.id,
      },
    });
    dispatch({
      type: 'risk/getApprovalList',
      payload: {
        projectId: params.id,
      },
    });
    window.addEventListener('resize', this.resizeFooterToolbar);
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.resizeFooterToolbar);
  }

  resizeFooterToolbar = () => {
    const sider = document.querySelectorAll('.ant-layout-sider')[0];
    const width = `calc(100% - ${sider.style.width})`;
    if (this.state.width !== width) {
      this.setState({ width });
    }
  };

  renderCustomerFooter(creditVerify, customer, index) {
    // console.log("renderCustomerFooter", creditVerify)
    const { getFieldDecorator } = this.props.form;
    const formItemLayoutOfFooter = {
      labelCol: {
        span: 3,
      },
      wrapperCol: {
        span: 21,
      },
    };

    return (
      <FormItem label="审批意见" {...formItemLayoutOfFooter}>
        {getFieldDecorator(`creditVerify${index}`, {
          initialValue: creditVerify[index].creditVerify,
        })(
          <Radio.Group disabled>
            <Radio value={1}>
              <span style={{ color: 'green' }}>
                一致<Icon type="check" />
              </span>
            </Radio>
            <Radio value={0}>
              <span style={{ color: 'red' }}>
                不同<Icon type="close" />
              </span>
            </Radio>
          </Radio.Group>
        )}
      </FormItem>
    );
  }

  handleClickShow = () => {
    this.setState({
      modalVisible: true,
    });
  };

  handleModalCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  // handleReviewSubmit = () => {
  //   const { dispatch } = this.props;
  //   const { validateFieldsAndScroll } = this.props.form;
  //   let result = null;
  //   validateFieldsAndScroll((error, values) => {
  //     if (!error) {
  //       if (values.resultCode == '1') {
  //         result = "通过"
  //       }
  //       if (values.resultCode == '2') {
  //         result = "驳回"
  //       }
  //       if (values.resultCode == '3') {
  //         result = "拒绝"
  //       }
  //       dispatch({
  //         type: 'risk/commitDoApproval',
  //         payload: {
  //           projectId: this.state.projectId,
  //           taskId: this.state.taskId,
  //           ...values,
  //           result: result,
  //           type: 2,
  //         },
  //         callback: () => {
  //           const { risk: { riskResult } } = this.props;
  //           if (riskResult.code == 200) {
  //             this.setState({
  //               modalVisible: false
  //             })
  //             message.success('提交成功');
  //             dispatch(routerRedux.push('/risk/reviewList'));
  //           } else {
  //             message.error(riskResult.message);
  //           }
  //         },
  //       });
  //     }
  //   });
  // }

  handleProgress = () => {
    this.setState({
      progressVisible: true,
    });
  };

  handleProgressModalCancel = () => {
    this.setState({
      progressVisible: false,
    });
  };

  progressColumns = [
    {
      title: '指标',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '初审',
      dataIndex: 'state',
      key: 'state',
      render: (text, item) => {
        return (
          <div>
            {/* {console.log("item.childrens", item)} */}
            {item.childrens.map(child => {
              if ((child.key == '1-1' || child.key == '4-1') && child.state) {
                return (
                  child.state != -1 &&
                  child.state.map(item => {
                    switch (item.relation) {
                      case 1:
                        return this.handleCustomeVerify('', item.verify, '主申请人身份认证');
                      case 2:
                        return this.handleCustomeVerify('', item.verify, '共同还款人身份认证');
                      case 3:
                        return this.handleCustomeVerify('', item.verify, '担保人身份认证');
                    }
                  })
                );
              } else {
                return this.handleCustomeVerify(child.key, child.state, child.name);
              }
            })}
          </div>
        );
      },
    },
  ];

  handleCustomeVerify = (key, state, name) => {
    switch (state) {
      case 1:
        return (
          <Tag color="green">
            {name} <Icon type="check" style={{ color: 'green' }} />
          </Tag>
        );
      case 0:
        return (
          <Tag color="red">
            {name} <Icon type="close" style={{ color: 'red' }} />
          </Tag>
        );
      case -1:
        return (
          <div>
            {key == '1-2' ? null : (
              <Tag>
                {name} <Icon type="minus" style={{ color: 'gray' }} />
              </Tag>
            )}
          </div>
        );
    }
  };

  haandleApprovalSubmit = () => {
    this.setState({
      approvalResult: true,
    });
  };

  handleApprovalReviewSubmit = () => {
    const { dispatch } = this.props;
    const { validateFieldsAndScroll } = this.props.form;
    let result = null;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        if (values.resultCode == '1') {
          result = '通过';
        }
        if (values.resultCode == '2') {
          result = '驳回';
        }
        if (values.resultCode == '3') {
          result = '拒绝';
        }
        dispatch({
          type: 'risk/commitDoApproval',
          payload: {
            projectId: this.state.projectId,
            taskId: this.state.taskId,
            ...values,
            result: result,
            type: 2,
          },
          callback: () => {
            const { risk: { riskResult } } = this.props;
            if (riskResult.code == 200) {
              this.setState({
                approvalResult: false,
              });
              message.success('提交成功');
              dispatch(routerRedux.push('/risk/reviewList'));
            } else {
              message.error(riskResult.message);
            }
          },
        });
      }
    });
  };

  handleApprovalModalCancel = () => {
    this.setState({
      approvalResult: false,
    });
  };

  handleReviewResultCode = code => {
    switch (code) {
      case 1:
        return '通过';
        break;
      case 2:
        return '驳回';
        break;
      case 3:
        return '否决';
        break;
    }
  };

  render() {
    const {
      risk: { riskBusinessDetails, riskLoading, riskApprovalList, riskHomeVisitLoading },
    } = this.props;
    const { getFieldDecorator } = this.props.form;

    const action = (
      <div style={{ flex: '1' }}>
        <ButtonGroup>
          <Button onClick={this.handleClickShow}>审批结果</Button>
          <Button onClick={this.handleProgress}>审批记录</Button>
        </ButtonGroup>
      </div>
    );

    return (
      <PageHeaderLayout
        title="业务复审详情"
        className={styles.channelDetailsContainer}
        action={action}
      >
        {/* {<Button>查看详情</Button>} */}
        {/* {JSON.stringify(riskBusinessDetails)} */}
        {riskLoading ? (
          <div className={styles.spinContainer}>
            <Spin size="large" />
          </div>
        ) : (
          riskBusinessDetails && (
            <div>
              <Card title="业务摘要" className={styles.preCheckFormCard}>
                {/* <ApplyOrderDisplayer /> */}
                {riskBusinessDetails.business && (
                  <DescriptionList className={styles.headerList} size="small" col="3">
                    <Description term="客户名称">
                      {riskBusinessDetails.business.custName}
                    </Description>
                    <Description term="证件号">{riskBusinessDetails.business.idcard}</Description>
                    <Description term="担保公司">
                      {riskBusinessDetails.business.orgName}
                    </Description>
                    <Description term="经销商">
                      {riskBusinessDetails.business.dealerName}
                    </Description>
                    <Description term="所购车型">
                      {riskBusinessDetails.business.carType}
                    </Description>
                    <Description term="车价">
                      {riskBusinessDetails.business.dealerPrice}
                    </Description>
                    <Description term="首付款">
                      {riskBusinessDetails.business.firstPayment}
                    </Description>
                    <Description term="分期金额">
                      {riskBusinessDetails.business.loanAmt}
                    </Description>
                    <Description term="分期数">
                      {riskBusinessDetails.business.loanDuration}
                    </Description>
                    <Description term="手续费率">
                      {riskBusinessDetails.business.intrest}%
                    </Description>
                    <Description term="手续费">{riskBusinessDetails.business.fee}</Description>
                  </DescriptionList>
                )}
              </Card>
              <Card title="详情复核" style={{ marginTop: '16px' }}>
                <Tabs tabPosition="left">
                  <TabPane
                    tab={
                      <span>
                        客户核实
                        {riskBusinessDetails.verifyStatus &&
                        riskBusinessDetails.verifyStatus.split('')[0] == '1' ? (
                          <Icon type="check" style={{ color: 'green' }} />
                        ) : (
                          <span style={{ marginRight: '22px' }} />
                        )}
                      </span>
                    }
                    key="1"
                  >
                    {/* <CustomerChecker hideThirdVerify={true} /> */}
                    {riskBusinessDetails.customerVerify && (
                      <CustomerChecker
                        hideThirdVerify={true}
                        checkDetailsValue={false}
                        projectId={this.state.projectId}
                      />
                    )}
                  </TabPane>
                  <TabPane
                    tab={
                      <span>
                        资产核实
                        {riskBusinessDetails.verifyStatus &&
                        riskBusinessDetails.verifyStatus.split('')[1] == '1' ? (
                          <Icon type="check" style={{ color: 'green' }} />
                        ) : (
                          <span style={{ marginRight: '22px' }} />
                        )}
                      </span>
                    }
                    key="2"
                  >
                    {/* <AssetChecker /> */}
                    {riskBusinessDetails.assetsVerify && (
                      <AssetChecker checkDetailsValue={false} projectId={this.state.projectId} />
                    )}
                  </TabPane>
                  <TabPane
                    tab={
                      <span>
                        收入核实
                        {riskBusinessDetails.verifyStatus &&
                        riskBusinessDetails.verifyStatus.split('')[2] == '1' ? (
                          <Icon type="check" style={{ color: 'green' }} />
                        ) : (
                          <span style={{ marginRight: '22px' }} />
                        )}
                      </span>
                    }
                    key="3"
                  >
                    {/* <RepaymentAbilityChecker /> */}
                    {riskBusinessDetails.incomeVerify && (
                      <RepaymentAbilityChecker
                        checkDetailsValue={false}
                        projectId={this.state.projectId}
                      />
                    )}
                  </TabPane>
                  <TabPane
                    tab={
                      <span>
                        资信调查
                        {riskBusinessDetails.verifyStatus &&
                        riskBusinessDetails.verifyStatus.split('')[3] == '1' ? (
                          <Icon type="check" style={{ color: 'green' }} />
                        ) : (
                          <span style={{ marginRight: '22px' }} />
                        )}
                      </span>
                    }
                    key="4"
                  >
                    {/* <CustomerList
                        hideDocuments={true}
                        customerFooter={this.renderCustomerFooter(riskBusinessDetails.creditVerify)}
                      /> */}
                    {riskBusinessDetails.creditVerify && (
                      <CustomerList
                        hideDocuments={true}
                        checkDetailsValue={false}
                        thirdPartyQuery={false}
                        projectId={this.state.projectId}
                        customerFooter={(customer, index) => {
                          return this.renderCustomerFooter(
                            riskBusinessDetails.creditVerify,
                            customer,
                            index
                          );
                        }}
                      />
                    )}
                    {/**/}
                  </TabPane>
                </Tabs>
              </Card>
            </div>
          )
        )}

        <FooterToolbar style={{ width: this.state.width }}>
          <Button type="primary" onClick={this.haandleApprovalSubmit}>
            提交
          </Button>
        </FooterToolbar>

        <Modal
          title={'审批提交'}
          visible={this.state.modalVisible}
          // onOk={this.handleReviewSubmit}
          onCancel={this.handleModalCancel}
          footer={null}
        >
          <Table
            columns={this.progressColumns}
            dataSource={riskBusinessDetails && riskBusinessDetails.verifyNote}
            size="small"
            rowKey="key"
            bordered={false}
            pagination={false}
            style={{ marginBottom: 20 }}
          />
        </Modal>
        <Modal
          title={'审批提交'}
          visible={this.state.approvalResult}
          onOk={this.handleApprovalReviewSubmit}
          onCancel={this.handleApprovalModalCancel}
          confirmLoading={riskHomeVisitLoading}
        >
          {riskBusinessDetails && (
            <Row>
              <Col span={24}>
                <FormItem label="初审结果" {...formItemLayout}>
                  {riskBusinessDetails.approval1 &&
                    this.handleReviewResultCode(riskBusinessDetails.approval1.resultCode)}
                </FormItem>
                <FormItem label="初审意见" {...formItemLayout}>
                  {riskBusinessDetails.approval1 && riskBusinessDetails.approval1.content}
                </FormItem>
              </Col>
            </Row>
          )}

          <Row>
            <Col span={24}>
              <FormItem label="审核结果" {...formItemLayout}>
                {getFieldDecorator('resultCode', {})(
                  <Radio.Group>
                    <Radio value="1">通过</Radio>
                    <Radio value="2">驳回</Radio>
                    <Radio value="3">否决</Radio>
                  </Radio.Group>
                )}
              </FormItem>
              <FormItem label="审核意见" {...formItemLayout}>
                {getFieldDecorator('content', {})(<TextArea rows={4} />)}
              </FormItem>
            </Col>
          </Row>
        </Modal>
        <Modal
          title="审批记录"
          keyboard={true}
          footer={null}
          visible={this.state.progressVisible}
          onCancel={this.handleProgressModalCancel}
        >
          <Collapse>
            {riskApprovalList &&
              riskApprovalList.map(item => {
                return (
                  <Panel header={item.displayName + '  ' + item.createTime} key={item.id}>
                    <p>任务名称：{item.displayName}</p>
                    <p>创建时间：{item.createTime}</p>
                    <p>完成时间：{item.updateTime}</p>
                    <p>任务处理人：{item.opname}</p>
                    <p>任务处理结果：{item.result}</p>
                    <p>意见：{item.content}</p>
                  </Panel>
                );
              })}
          </Collapse>
        </Modal>
        {/* <FooterToolbar style={{ width: this.state.width }}>
          <Button type="primary">提交</Button>
        </FooterToolbar> */}
      </PageHeaderLayout>
    );
  }
}
